<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd"
              > 
                新增角色
              </el-button>
            </el-row>
            <!-- 表格 -->
            <el-table
              :data="roles"
              style="width: 100%;"
            >
              <!-- type:index会自动生成序号 -->
              <el-table-column
                label="序号"
                type="index"
                width="60"
              />
              <el-table-column
                prop="name"
                label="角色名称"
                width="180"
              />
              <el-table-column
                prop="description"
                label="描述"
              />
              <el-table-column
                width="300"
                label="操作"
              >
                <template #default="{row}">
                  <el-button
                    size="small"
                    type="success"
                    @click="onAssignRole(row.id)"
                  >
                    分配权限
                  </el-button>
                  <el-button 
                    size="small"
                    @click="hEdit(row)"
                  >
                    编辑
                  </el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="loadDeleteRole(row.id)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-row
              type="flex"
              justify="center"
              align="middle"
              style="height: 60px"
            >
              <!-- 分页组件 -->
              <el-pagination
                v-model:currentPage="pageParams.page"
                v-model:page-size="pageParams.pagesize"
                :page-sizes="[2, 5, 10, 20]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pageParams.total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 新增弹框 -->
      <el-dialog
        v-model="showDialog" 
        title="编辑弹层"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        @close="resetForm(refForm)"
      >
        <el-form
          ref="refForm"
          :model="roleForm"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item
            label="角色名称"
            prop="name"
          >
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item
            label="角色描述"
            prop="description"
          >
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row
          type="flex"
          justify="center"
        >
          <el-col :span="6">
            <el-button
              size="small"
              @click="resetForm(refForm)"
            >
              取消
            </el-button>
            <el-button
              size="small"
              type="primary"
              @click="submitForm(refForm)"
            >
              确定
            </el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <el-dialog
        v-model="showAssignRoleDialog"
        title="分配权限"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        @close="showAssignRoleDialog=false"
      >
        <AssignPermission
          :id="curId"
          ref="assignRole"
          @close="showAssignRoleDialog=false"
          @success="onSuccess"
        ></AssignPermission>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getRoles ,addRole,deleteRole ,updateRole } from '@/api/settings'
import type { FormInstance, FormRules } from 'element-plus'
import AssignPermission from './assignPermission.vue'
//分配权限
//分配权限
const assignRole=ref()
const showAssignRoleDialog=ref(false)
const curId=ref('')
const onAssignRole=(id:string) => {
  showAssignRoleDialog.value=true
  curId.value=id
  nextTick(() => {
    assignRole.value.loadProfileById()
  })
}
const onSuccess=() => {
  showAssignRoleDialog.value=false
}

//初始化
const pageParams=reactive({
  page:1,
  pagesize:2,
  total:0,
})
const roles=ref<RoleForm[]>()
const loadRoles =async() => {
  try {
    const res = await getRoles(pageParams)
    console.log('getRoles',res)
    roles.value=res.data.rows
    pageParams.total=res.data.total
  } catch (error) {
    console.log(error)
  }
}
loadRoles()
//分页控制
const handleSizeChange = (val: number) => {
  console.log(`${ val } items per page`)
  pageParams.pagesize=val
  loadRoles()
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${ val }`)
  pageParams.page=val
  loadRoles()
}
//控制弹层
const showDialog=ref(false)
//表单验证
const refForm = ref<FormInstance>()
let roleForm=reactive({
  name:'',
  description:'',
})
const rules = reactive<FormRules>({
  name: [
    { required: true, message: 'Please input Activity name', trigger: 'blur' },
  ],
  description: [
    { required: true, message: 'Please input Activity name', trigger: 'blur' },
  ],
})
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if(!valid) return
    isEdit.value ? loadUpdateRole() : loadAddRole()
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  showDialog.value=false
  roleForm.name=''
  roleForm.description=''
  console.log(' roleForm', roleForm)
}
//删除角色
const loadDeleteRole =async(id:string) => {
  try {
    await ElMessageBox.confirm('你确定删除吗?')
    const res = await deleteRole(id)
    console.log('deleteRole',res)
    if(roles.value?.length===1) pageParams.page--
    if(pageParams.page<=0) pageParams.page=1
    loadRoles()
  } catch (error) {
    console.log(error)
  }
}
//新增角色
const hAdd=() => {
  showDialog.value=true
  isEdit.value=false
}
const loadAddRole =async() => {
  try {
    const res = await addRole(roleForm)
    console.log('addRole',res)
    pageParams.total++
    pageParams.page= Math.ceil(pageParams.total/pageParams.pagesize)
    loadRoles()
    showDialog.value=false
  } catch (error) {
    console.log(error)
  }
}
//编辑角色
const isEdit=ref(false)
const hEdit=(row:RoleForm) => {
  showDialog.value=true
  isEdit.value=true
  roleForm=Object.assign(roleForm,row)
}
const loadUpdateRole =async() => {
  try {
    const res = await updateRole(roleForm)
    console.log('updateRole',res)
    showDialog.value=false
    loadRoles()
  } catch (error) {
    console.log(error)
  }
}

</script>

<style lang="scss">
  .el-dialog__header {
    margin-right: 0;
  }

</style>